package hos.demo

import android.content.Context
import android.content.DialogInterface
import android.location.Location
import android.os.Bundle
import android.os.Parcelable
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.FileIOUtils
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.PermissionUtils
import hos.cache.StorageFile
import hos.cache.StorageSp
import hos.demo.databinding.ActivityMainBinding
import hos.location.LocationSource
import hos.location.LocationSourceAndroidData
import hos.location.LocationSourceAndroidDataCache

class MainActivity : AppCompatActivity() {
    private val activityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    private val locationSource: LocationSource by lazy { LocationSourceAndroidDataCache(this); }
    private var location: LocationSource.Location? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(activityMainBinding.getRoot())
        if (location == null) {
            location = locationSource.location
        }
        activityMainBinding.btn1.setOnClickListener(View.OnClickListener {
            val isSuccess: Boolean = StorageFile.saveCache("file", "张三")
            Toast.makeText(this@MainActivity, "是否成功：$isSuccess", Toast.LENGTH_SHORT).show()
        })
        activityMainBinding.btn2.setOnClickListener(View.OnClickListener {
            val value: String = StorageFile.getData("file")
            Toast.makeText(this@MainActivity, "结果：$value", Toast.LENGTH_SHORT).show()
        })
        activityMainBinding.btn3.setOnClickListener(View.OnClickListener {
            val start = System.currentTimeMillis()
            val user = User(System.currentTimeMillis(), "张三", "12345678", false)
            val isSuccess: Boolean = StorageFile.saveCache("location", location)
            if (location is LocationSourceAndroidData.LocationData) {
                StorageFile.saveCache(
                    "androidLocation",
                    (location as LocationSourceAndroidData.LocationData).location as Parcelable
                )
            }
            val end = System.currentTimeMillis()
            Log.i("TAG", "time: " + (end - start))
            Toast.makeText(this@MainActivity, "是否成功：$isSuccess", Toast.LENGTH_SHORT).show()
        })
        activityMainBinding.btn4.setOnClickListener(View.OnClickListener {
            val start = System.currentTimeMillis()
            var value: LocationSource.Location? =
                StorageFile.getData("location", LocationSource.Location.CREATOR)
            val end = System.currentTimeMillis()
            Log.i("TAG", "time: " + (end - start))
            if (value != null) {
                val androidLocation: Location? =
                    StorageFile.getData("androidLocation", Location.CREATOR)
                if (androidLocation == null) {
                    value = LocationSourceAndroidData.LocationData(value)
                } else {
                    value = LocationSourceAndroidData.LocationData(value, androidLocation)
                }
                Toast.makeText(this@MainActivity, "结果：$value", Toast.LENGTH_SHORT)
                    .show()
            } else {
                Toast.makeText(this@MainActivity, "结果：失败", Toast.LENGTH_SHORT).show()
            }
        })
        activityMainBinding.btn5.setOnClickListener(View.OnClickListener {
            val start = System.currentTimeMillis()
            val user = User(System.currentTimeMillis(), "李四", "12345678", false)
            val isSuccess: Boolean = StorageSp.saveCache("userSP", user)
            val end = System.currentTimeMillis()
            Log.i("TAG", "time: " + (end - start))
            Toast.makeText(this@MainActivity, "是否成功：$isSuccess", Toast.LENGTH_SHORT).show()
        })
        activityMainBinding.btn6.setOnClickListener(View.OnClickListener {
            val start = System.currentTimeMillis()
            val value: User = StorageSp.getData("userSP")
            val end = System.currentTimeMillis()
            Log.i("TAG", "time: " + (end - start))
            if (value != null) {
                Toast.makeText(this@MainActivity, "结果：$value", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this@MainActivity, "结果：失败", Toast.LENGTH_SHORT).show()
            }
        })
        activityMainBinding.btn7.setOnClickListener(View.OnClickListener {
            val start = System.currentTimeMillis()
            val clearSp: Boolean = StorageSp.clear()
            val clearFile: Boolean = StorageFile.clear()
            val end = System.currentTimeMillis()
            Log.i("TAG", "time: " + (end - start))
            Toast.makeText(this@MainActivity, "结果：sp:$clearSp file:$clearFile", Toast.LENGTH_SHORT)
                .show()
        })
        locationSource.addLocationChangedListener { location = it.getLocation() }

        request(this, object : PermissionUtils.SimpleCallback {
            override fun onGranted() {
                locationSource.startLocation()
            }

            override fun onDenied() {}
        }, DialogInterface.OnClickListener { _, _ -> }, PermissionConstants.LOCATION)
    }

    override fun onDestroy() {
        locationSource.stopLocation()
        super.onDestroy()
    }

    fun request(
        context: Context,
        callback: PermissionUtils.SimpleCallback?,
        cancelListener: DialogInterface.OnClickListener,
        vararg permissions: String
    ) {
        PermissionUtils.permission(*permissions)
            .rationale { activity, shouldRequest -> showRationaleDialog(activity, shouldRequest) }
            .callback(object : PermissionUtils.SingleCallback {
                override fun callback(
                    isAllGranted: Boolean,
                    granted: MutableList<String>,
                    deniedForever: MutableList<String>,
                    denied: MutableList<String>
                ) {
                    if (isAllGranted) {
                        callback?.onGranted()
                        return
                    }
                    if (deniedForever.isNotEmpty()) {
                        showOpenAppSettingDialog(context, cancelListener)
                        return
                    }
                    callback?.onDenied()
                }
            })
            .request()
    }

    private fun showRationaleDialog(
        context: Context,
        shouldRequest: PermissionUtils.OnRationaleListener.ShouldRequest
    ) {
        val message = "您已经拒绝我们的授权申请，请同意授权，否则该功能无法正常使用! "
        AlertDialog.Builder(context)
            .setCancelable(false)
            .setTitle("温馨提示")
            .setMessage(message)
            .setNegativeButton("取消") { _: DialogInterface, _: Int ->
                shouldRequest.again(
                    false
                )
            }
            .setPositiveButton("授权") { _: DialogInterface, _: Int ->
                shouldRequest.again(
                    true
                )
            }
            .show()
    }

    private fun showOpenAppSettingDialog(
        context: Context,
        cancelListener: DialogInterface.OnClickListener
    ) {
        AlertDialog.Builder(context)
            .setCancelable(false)
            .setTitle("温馨提示")
            .setMessage("我们需要一些您拒绝的权限或系统申请失败的权限失败，请手动设置为页面授权，否则该功能无法正常使用! ")
            .setNegativeButton("取消", cancelListener)
            .setPositiveButton(
                "授权"
            ) { _: DialogInterface, _: Int -> PermissionUtils.launchAppDetailsSettings() }
            .show()
    }
}